package com.christina.service.domain.chat.impl;

import com.christina.service.domain.chat.ChatDomainService;
import com.christina.service.domain.chat.model.ChatRequest;
import com.christina.service.domain.chat.model.ChatResponse;
import com.christina.service.CacheService;
import com.christina.service.MessageQueueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * 聊天领域服务实现
 * 
 * @author Christina
 */
@Slf4j
@Service
public class ChatDomainServiceImpl implements ChatDomainService {

    private final ChatClient chatClient;
    private final CacheService cacheService;
    private final MessageQueueService messageQueueService;

    public ChatDomainServiceImpl(ChatClient chatClient, CacheService cacheService, MessageQueueService messageQueueService) {
        this.chatClient = chatClient;
        this.cacheService = cacheService;
        this.messageQueueService = messageQueueService;
    }

    @Override
    public ChatResponse processChat(ChatRequest request) {
        log.info("处理聊天消息: userId={}, sessionId={}", request.getUserId(), request.getSessionId());
        
        try {
            // 构建聊天提示词
            String prompt = buildChatPrompt(request);
            
            // 调用AI获取回复
            String aiResponse = chatClient.prompt(prompt).call().content();
            
            // 分析情感
            ChatResponse.SentimentAnalysis sentiment = analyzeSentiment(request.getMessage());
            
            // 生成建议操作
            java.util.List<ChatResponse.SuggestedAction> actions = generateSuggestedActions(request, aiResponse);
            
            // 构建响应
            ChatResponse response = ChatResponse.builder()
                .content(aiResponse)
                .responseType(ChatResponse.ResponseType.ANSWER)
                .suggestedActions(actions)
                .sentiment(sentiment)
                .responseTime(LocalDateTime.now())
                .build();
            
            // 发送到消息队列进行异步处理
            messageQueueService.sendChatMessage(request.getUserId(), request.getMessage());
            
            log.info("聊天消息处理完成: userId={}", request.getUserId());
            return response;
            
        } catch (Exception e) {
            log.error("聊天消息处理失败", e);
            return ChatResponse.builder()
                .content("抱歉，我暂时无法理解您的问题，请稍后重试。")
                .responseType(ChatResponse.ResponseType.ANSWER)
                .responseTime(LocalDateTime.now())
                .build();
        }
    }

    @Override
    public Flux<String> processChatStream(ChatRequest request) {
        log.info("处理流式聊天: userId={}, sessionId={}", request.getUserId(), request.getSessionId());
        
        try {
            String prompt = buildChatPrompt(request);
            
            // 调用AI获取流式回复
            Flux<String> responseFlux = chatClient.prompt(prompt).stream().content();
            
            // 收集完整回复并异步处理
            StringBuilder fullResponse = new StringBuilder();
            return responseFlux.doOnNext(chunk -> {
                fullResponse.append(chunk);
            }).doOnComplete(() -> {
                // 发送完整消息到队列
                messageQueueService.sendChatMessage(request.getUserId(), fullResponse.toString());
            });
            
        } catch (Exception e) {
            log.error("流式聊天处理失败", e);
            return Flux.just("抱歉，服务暂时不可用，请稍后重试。");
        }
    }

    @Override
    public Object getChatHistory(Long userId, String sessionId, int limit) {
        log.info("获取聊天历史: userId={}, sessionId={}, limit={}", userId, sessionId, limit);
        
        try {
            // 从缓存获取聊天历史
            Object cachedHistory = cacheService.getCachedUserInfo(userId);
            if (cachedHistory != null) {
                return cachedHistory;
            }
            
            // 如果缓存没有，从数据库查询（这里简化处理）
            return new ArrayList<>();
            
        } catch (Exception e) {
            log.error("获取聊天历史失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public boolean clearChatHistory(Long userId, String sessionId) {
        log.info("清除聊天历史: userId={}, sessionId={}", userId, sessionId);
        
        try {
            // 清除缓存
            cacheService.clearUserInfoCache(userId);
            
            // 清除数据库记录（这里简化处理）
            
            return true;
            
        } catch (Exception e) {
            log.error("清除聊天历史失败", e);
            return false;
        }
    }

    @Override
    public Object analyzeChatSentiment(String message) {
        log.info("分析聊天情感: {}", message);
        
        try {
            String prompt = String.format("""
                请分析以下文本的情感倾向：
                
                文本：%s
                
                请返回：
                1. 情感类型（positive/negative/neutral）
                2. 置信度（0-1）
                3. 具体情绪（happy/sad/angry/excited等）
                
                以JSON格式返回结果。
                """, message);
            
            String aiResponse = chatClient.prompt(prompt).call().content();
            
            // 解析AI响应（这里简化处理）
            return ChatResponse.SentimentAnalysis.builder()
                .sentiment("neutral")
                .confidence(0.8)
                .emotion("calm")
                .build();
            
        } catch (Exception e) {
            log.error("情感分析失败", e);
            return null;
        }
    }

    /**
     * 构建聊天提示词
     */
    private String buildChatPrompt(ChatRequest request) {
        return String.format("""
            你是Christina，一个智能助手。请友好、专业地回答用户的问题。
            
            用户消息：%s
            
            请提供有用、准确的回答。如果涉及出行规划、任务管理等专业领域，
            请提供详细的建议和指导。
            """, request.getMessage());
    }

    /**
     * 分析情感
     */
    private ChatResponse.SentimentAnalysis analyzeSentiment(String message) {
        // 简化的情感分析实现
        String lowerMessage = message.toLowerCase();
        
        if (lowerMessage.contains("谢谢") || lowerMessage.contains("好的") || lowerMessage.contains("棒")) {
            return ChatResponse.SentimentAnalysis.builder()
                .sentiment("positive")
                .confidence(0.8)
                .emotion("happy")
                .build();
        } else if (lowerMessage.contains("不行") || lowerMessage.contains("失败") || lowerMessage.contains("错误")) {
            return ChatResponse.SentimentAnalysis.builder()
                .sentiment("negative")
                .confidence(0.7)
                .emotion("frustrated")
                .build();
        } else {
            return ChatResponse.SentimentAnalysis.builder()
                .sentiment("neutral")
                .confidence(0.6)
                .emotion("calm")
                .build();
        }
    }

    /**
     * 生成建议操作
     */
    private java.util.List<ChatResponse.SuggestedAction> generateSuggestedActions(ChatRequest request, String aiResponse) {
        java.util.List<ChatResponse.SuggestedAction> actions = new ArrayList<>();
        
        // 基于AI响应内容生成建议操作
        if (aiResponse.contains("出行") || aiResponse.contains("旅游")) {
            actions.add(ChatResponse.SuggestedAction.builder()
                .actionId("travel_planning")
                .actionText("制定出行计划")
                .actionType("TRAVEL_PLAN")
                .actionData("开始出行规划")
                .build());
        }
        
        if (aiResponse.contains("帮助") || aiResponse.contains("更多")) {
            actions.add(ChatResponse.SuggestedAction.builder()
                .actionId("get_help")
                .actionText("获取更多帮助")
                .actionType("HELP")
                .actionData("显示帮助信息")
                .build());
        }
        
        return actions;
    }
}